package com.example.graduation.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 文件工具类
 *
 * @author thq
 */
@Service
@Slf4j(topic = "FileUtil")
public class FileUtil {

    /**
     * 判断文件是否为空
     *
     * @return boolean
     */
    public boolean isEmpty(MultipartFile file) {
        return file.isEmpty();
    }

    /**
     * 获取当前文件名
     *
     * @return string
     */
    public String getFileName(MultipartFile file) {
        return file.getOriginalFilename();
    }

    /**
     * 获取文件后缀名
     *
     * @return string
     */
    public String getFileSuffixName(MultipartFile file) {
        String result = "";
        if (!isEmpty(file)) {
            result = FilenameUtils.getExtension(getFileName(file));
        }
        return result;
    }

    /**
     * 将file转成byte[]
     *
     * @return byte[]
     */
    public byte[] fileToByte(File tradeFile) {
        byte[] result = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            result = bos.toByteArray();
        } catch (Exception e) {
            log.error("发生异常了：" + e.getMessage());
        }
        return result;
    }
}
